<!-- 组织信息 -->
<template>
  <div class="">
    <el-row :gutter="10">
      <el-col :span="6">
        <el-card class="box-card">
          <el-input placeholder="输入关键字进行过滤" v-model.trim="filterText">
          </el-input>
          <el-tree class="filter-tree" :load="loadNode" :props="defaultProps" :filter-node-method="filterNode"
            :expand-on-click-node="false" :current-node-key="currentNodeKey" node-key="id"
            :default-expanded-keys="state.defaultExpandedKeys" highlight-current lazy @node-click="handleNodeClick"
            ref="treeRef">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span>
                  <el-button type="primary" text size="small" v-if="node.level !== 2"
                    @click.stop="e => handleAppend(node, data, e)">
                    新增
                  </el-button>
                  <el-button text size="small" class="red ml0" v-if="node.level !== 1"
                    @click.stop="e => handleRemove(node, data, e)">
                    删除
                  </el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card class="box-card">
          <el-form label-width="120px" :model="organizationForm" :rules="rules" :highlight-current="true"
            v-loading="loadingDialog" ref="organizationFormRef">
            <el-row :gutter="10">
              <el-col :span="7">
                <el-form-item label="组织名称：" prop="name">
                  <el-input v-model.trim="organizationForm.name" placeholder="点击左侧新增后添加组织名称"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-row :gutter="10">
            <el-col :span="6" :offset="1">
              <el-button type="primary" :icon="Check" :disabled="disabledbtn"
                @click="submitForm(organizationFormRef, organizationForm, methodType, 'commonOrganizationInfo', 'getOrganizationInfo')">保存</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="20" :offset="1">
              <ul>
                <li>描述：用于描述公司的组织架构（或公司的部门）</li>
              </ul>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import { reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { View, Search, Refresh, Check } from '@element-plus/icons-vue';
import { common as Common } from '@/utils/common.js';
import { api as Request, imageUrl, uploadUrl } from '@/utils/api';
const state = reactive({
  defaultExpandedKeys: [0]/* 默认显示哪几级信息 */
});
const filterText = ref('');
const treeRef = ref('');
const organizationFormRef = ref('');
const defaultProps = reactive({
  children: 'children',
  label: 'name',
  isLeaf: 'leaf'
})
const currentNodeKey = ref('');/* 当前选中的节点 */
const searchCondition = reactive({
  paid: 0
})
const methodType = ref('POST');/* 请求类型 */

const organizationForm = reactive({
  id: '',
  name: ''
})
const rules = {
  name: [{ required: true, message: '请填写组织名称', trigger: 'blur' }]
}

const delVisibleType = ref('delete');/* 删除类型（单选，多选） */
const loadingDialog = ref(false);/* */
const disabledbtn = ref(false); /* 可用与不可用 */
const node = ref(''); /* 删除时的节点与节点数据 */
const node_had = ref('');/* */
const isParent = ref(true);/* */
const id = ref('');

/* 过滤节点信息 */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.title.indexOf(value) !== -1;
}

/* 更新tree中某个结点 */
const handleUpdateTree = () => {
  // 通过ID利用DOM找到该结点
  const node = treeRef.value.getNode(node_had.value);
  const tempNode = isParent.value ? node.parent : node;
  // 更改该结点属性
  tempNode.loaded = false;
  // 手动调用该结点数据加载方法
  tempNode.loadData();
}
/* 点击获取节点信息 */
const handleNodeClick = (data, node) => {
  node_had.value = node;
  isParent.value = true;
  organizationForm.id = data.id;
  organizationForm.name = data.name;
  if (data.id !== '') {
    /* 修改 */
    methodType.value = 'PUT';
  } else {
    /* 新增 */
    methodType.value = 'POST';
  }
}
/* 数据初始化 */
const handleInitData = () => {
  methodType.value = 'POST';
  organizationForm.id = '';
  organizationForm.name = '';
}
/* 添加节点 */
const handleAppend = (node, data, e) => {
  if (!node.loaded) {
    ElMessage.warning(
      `请先点击左侧小箭头，加载下级，再进行新增下级操作`
    );
    return;
  }
  e.stopPropagation();
  isParent.value = false;
  const childNodes = node.childNodes;
  for (let i = 0; i < childNodes.length; i++) {
    if (childNodes[i].data.id === '') return;
  }
  const newChild = {
    id: '',
    name: '',
    leaf: true,
    children: []
  };

  if (!data.children) {
    data.children = []
  }
  data.children.push(newChild);

  node_had.value = node;
  handleInitData();
}
/* 删除节点 */
const handleRemove = (node, data, e) => {
  isParent.value = true;
  e.stopPropagation();
  if (data.id === '') {
    const parent = node.parent;
    const children = parent.data.children || parent.data;
    const index = children.findIndex((d) => d.id === data.id);
    children.splice(index, 1);
    node.parent.loaded = false;
    node.parent.loadData();
    handleInitData();
  } else {
    id.value = data.id;
    /* 发送请求id 去删除数据 */
    delVisibleType.value = 'delete';
    deleteMessageBox('deleteOrganizationInfo');
  }
}
/* 加载节点数据 */
const loadNode = async (node, resolve) => {
  node_had.value = node;
  if (node.level === 0) {
    const data = {
      id: 0,
      name: '组织管理',
      children: []
    };
    return resolve([data]);
  }
  // if (node.data.id === '') return resolve([]);
  try {
    if (node.level === 0) {
      searchCondition.paid = '';
    } else {
      searchCondition.paid = node.data.id;
    }
    const res = await Request.getOrganizationInfo();
    if (res.status === 1 && res.result.length !== 0) {
      res.result.forEach((item) => {
        item.leaf = true;
      });
      return resolve(res.result);
    }
    return resolve([]);
  } catch (error) {
    console.log(error);
    return resolve([]);
  }
}
/* 保存或编辑 */
const submitForm = (formEl, formData, type, method, refreshMethod) => {
  if (isParent.value && node_had.data && node_had.data.id === 0) {
    ElMessage.warning(`'组织管理'目录不能修改`);
    return;
  }
  formEl.validate((valid) => {
    if (valid) {
      submitFormInfo(formData, type, method, refreshMethod);
    } else {
      /* 提示还有需要填写的信息 */
      ElMessage.warning('请填写所有必填信息');
      return false;
    }
  });
}
/* 保存或编辑信息 */
const submitFormInfo = (formData, type, method, refreshMethod) => {
  /* 防止多次提交 */
  disabledbtn.value = true;
  loadingDialog.value = true;
  Request[method](formData, type)
    .then((res) => {
      ElMessage.success(res.msg);
      handleUpdateTree();
      handleInitData();
    })
    .catch((res) => { }).finally(() => {
      disabledbtn.value = false;
      loadingDialog.value = false;
    });
}
/* 打开删除弹框 */
const deleteMessageBox = (method) => {
  ElMessageBox.confirm('删除不可恢复，是否确定删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteInfo({ idArray: id.value }, method);
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
}
/* 删除后的信息 */
const deleteInfo = (data, method) => {
  disabledbtn.value = true;
  Request[method](data)
    .then((res) => {
      handleUpdateTree();
      handleInitData();
      ElMessage.success(`删除数据成功`);
    })
    .catch((res) => { }).finally(() => { disabledbtn.value = false; });
}

/* 监听筛选数据 */
watch(filterText, (val) => {
  treeRef.value.filter(val)
})
</script>

<style scoped>
.el-row {
  margin-bottom: 15px;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

.el-tree {
  height: 740px;
  overflow: scroll;
}

.red {
  color: #f00;
}

:deep(.el-tree-node__label) {
  width: 100%
}

.ml0 {
  margin-left: 0;
}
</style>
